package test.study.db.sql.ddl;

import lombok.SneakyThrows;

import java.sql.*;

public class ExportPostgresTableDDL {

    @SneakyThrows
    public static void main(String[] args) {
// 数据库连接配置
        String url = "jdbc:mysql://127.0.0.1:3306/ds_mysql";
        String username = "root";
        String password = "root";

        // 连接数据库
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, username, password);

            // 获取数据库元数据
            DatabaseMetaData metaData = conn.getMetaData();

            // 获取所有表的建表语句
            ResultSet resultSet = metaData.getTables(null, null, "%", new String[]{"TABLE"});
            while (resultSet.next()) {
                String tableName = resultSet.getString("TABLE_NAME");
                String catalog = resultSet.getString("TABLE_CAT");
                String schema = resultSet.getString("TABLE_SCHEM");
                String tableType = resultSet.getString("TABLE_TYPE");
                String remarks = resultSet.getString("REMARKS");

                System.out.println("Table Name: " + tableName);
                System.out.println("Catalog: " + catalog);
                System.out.println("Schema: " + schema);
                System.out.println("Table Type: " + tableType);
                System.out.println("Remarks: " + remarks);

                // 获取单个表的建表语句
                ResultSet rs = metaData.getTables(catalog, schema, tableName, null);
                if (rs.next()) {
                    String createTableSql = rs.getString("CREATE_TABLE");
                    System.out.println(createTableSql);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
